import { onMounted, nextTick } from "vue";
import { getCss } from "@/share/helper";
// 点击事件: x/y、clientX/clientY、offsetX/offsetY、pageX/pageY、screenX/screenY、layerX/layerY
// 元素: offsetHeight|offsetWidth|offsetTop|offsetLeft、clientHeight|...、scrollHeight...
function Drag(containerDOMSelector, dragSelector, distance) {
  // distance{top:*px, left: *px} 是定位父元素距离 客户端区域顶端、左端的值
  // 因为使用的鼠标距离　clientX、clientY　是距离客户端区域的位置
  const containerDOM = document.querySelector(containerDOMSelector);
  const dragDOM = document.querySelector(dragSelector);
  // 问题1，资源还没获取回来时，高度不好定  img图片
  const containerH = 1010;
  const containerW = containerDOM.clientWidth;
  const dragW = dragDOM.offsetWidth;
  const dragH = dragDOM.offsetHeight;
  let dragOffsetX = 0;
  let dragOffsetY = 0;
  console.log("containerDOM", containerW);
  console.log("dragDOM", dragDOM);
  console.log("getCss", getCss(dragDOM, "left"), getCss(dragDOM, "top"));
  function mousemoveFunc(e) {
    console.log("mousemove", e);
    console.log("e.clientX, e.clientY", e.clientX, e.clientY);
    let left = e.clientX - distance.left - dragOffsetX;
    let top = e.clientY - distance.top - dragOffsetY;
    console.log("mouse", left, top);
    console.log(
      dragOffsetX,
      dragOffsetY,
      containerH - dragH,
      containerW - dragW
    );
    if (left < 0) {
      left = 0;
    }
    if (top < 0) {
      top = 0;
    }
    if (top > containerH - dragH) {
      top = containerH - dragH;
    }
    if (left > containerW - dragW) {
      left = containerW - dragW;
    }
    dragDOM.style.top = top + "px";
    dragDOM.style.left = left + "px";
  }
  dragDOM.onmousedown = function (e) {
    dragOffsetX = e.offsetX;
    dragOffsetY = e.offsetY;
    // 拖动的元素的mousedown
    console.log("dragDOM --- e ", e);
    containerDOM.onmousemove = function (e) {
      mousemoveFunc(e);
    };
  };
  document.onmouseup = function (e) {
    containerDOM.onmousemove = null;
  };
}
export default Drag;
